import Http from '@/utils/Http'

export default function(apiUrl: string, apiType?: string) {
  return function (target: any, methodName: string, descriptor: TypedPropertyDescriptor<any>): TypedPropertyDescriptor<any> {
    console.log('httpGet')
    const oldValue = descriptor.value
    let decorateData:object = target[methodName].__DECORATE_DATA
    descriptor.value = async function () {
      const args: Array<any> = [];
      for (let index:number = 0; index < arguments.length; index++) {
        args.push(arguments[index]);
      }
      console.log(`${process.env.VUE_APP_API_URL}`)
      let httpInstance = new Http(`${process.env.VUE_APP_API_URL}`)
      // let isHttp = httpInstance instanceof decorateData.params[0].paramMetaData
      // console.log("httpInstance", isHttp)
      let url:string = apiUrl
      let type:string = apiType ?? 'auto'

      if (type === 'customize') {
        return handleCustomizeHttp(decorateData, args, oldValue, this)
      } else {
        return await handleAutoHttp(decorateData, httpInstance, url, args)
      }
    }
    return descriptor
  }
}

async function handleAutoHttp(decorateData: any,httpInstance: Http, url: string, args: object) {
  try {
    let response = await httpInstance.get(url, {
      headers: decorateData?.headers ?? {},
      params: args
    })
    console.log('response', response)
    return response.data
  } catch (e) {
    return e
  }
}

function handleCustomizeHttp(decorateData: any, args: Array<any>, oldValue: any, instance: any) {
  // 数据注入
  for (let index:number = 0; index < decorateData?.params?.length ?? []; index++) {
    let paramData = decorateData?.params[index]
    if (paramData?.injectParamValue) {
      args.splice(paramData?.paramIndex, 0, paramData?.paramValue)
    }
  }
  // 执行原方法
  const value = oldValue.apply(instance, args);
}